<template>
	<el-form ref="loginFormRef" :model="loginFormData" size="large">
		<el-form-item
			prop="username"
			:rules="[
				{
					required: true,
					message: '用户名不能为空',
					trigger: 'blur',
				},
			]"
		>
			<el-input v-model="loginFormData.username" placeholder="请输入用户名" />
		</el-form-item>
		<el-form-item
			prop="password"
			:rules="[
				{
					required: true,
					message: '密码不能为空',
					trigger: 'blur',
				},
			]"
		>
			<el-input
				v-model="loginFormData.password"
				type="password"
				:show-password="true"
				placeholder="请输入密码"
			/>
		</el-form-item>
		<el-form-item
			prop="captcha"
			:rules="[
				{
					required: true,
					message: '验证码不能为空',
					trigger: 'blur',
				},
			]"
		>
			<el-input
				v-model="loginFormData.captcha"
				placeholder="请输入验证码"
				class="cap-input"
			/>
			<img class="captcha-img" :src="captchaImg" alt="验证码" />
		</el-form-item>
		<el-form-item>
			<el-button type="primary" :auto-insert-space="true" @click="login">
				登录
			</el-button>
		</el-form-item>
	</el-form>
</template>
<script setup>
import { onMounted, reactive, ref } from 'vue'
import { getCaptchaApi, loginApi } from '@/api/api.js'
import useAdminStore from '@/store/index.js'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const captchaImg = ref()
const userInfoStore = useAdminStore()
const router = useRouter()
const loginFormData = reactive({
	username: '',
	password: '',
	captcha: '',
	captchaId: '',
})

const loginFormRef = ref()
const getCaptchaImg = async () => {
	let res = await getCaptchaApi()
	captchaImg.value = res.picPath
	loginFormData.captchaId = res.captchaId
}
const login = async () => {
	try {
		await loginFormRef.value.validate()
		let res = await loginApi(loginFormData)
		ElMessage.success('登录成功')
		Object.assign(userInfoStore.userInfo, res.user)
		sessionStorage.setItem('token', res.token)
		await router.push('/')
	} catch (err) {
		await getCaptchaImg()
	}
}

onMounted(() => {
	getCaptchaImg()
})
</script>

<style scoped>
.captcha-img {
	height: 34px;
	margin-left: 8px;
}
.cap-input {
	width: calc(100% - 110px);
}
:deep(.el-button) {
	display: block;
	width: 100%;
}
</style>
